package com.cby.web.encrypt;

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RsaEncryptUtils {

    /** 非对称加密密钥算法*/
    public static final String RSA = "RSA";
    /** 加密填充方式*/
    public static final String ECB_PKCS1_PADDING = "RSA/ECB/PKCS1Padding";
    /** 秘钥默认长度*/
    public static final int DEFAULT_KEY_SIZE = 2048;
    /** 当要加密的内容超过bufferSize，则采用partSplit进行分块加密*/
    public static final byte[] DEFAULT_SPLIT = "#PART#".getBytes();
    /** 当前秘钥支持加密的最大字节数*/
    public static final int DEFAULT_BUFFER_SIZE = (DEFAULT_KEY_SIZE / 8) - 11;

    /**
     * 随机生成RSA密钥对
     *
     * @param keyLength 密钥长度，范围：512～2048  一般1024
     * @return
     */
    public static KeyPair generateRSAKeyPair(int keyLength) {
        try {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
            kpg.initialize(keyLength);
            return kpg.genKeyPair();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 用公钥对字符串进行加密
     *
     * @param data 原文
     * @param publicKey 公钥
     * @return 密文
     */
    public static byte[] encryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {
        // 得到公钥
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
        KeyFactory kf = KeyFactory.getInstance(RSA);
        PublicKey keyPublic = kf.generatePublic(keySpec);
        // 加密数据
        Cipher cp = Cipher.getInstance(ECB_PKCS1_PADDING);
        cp.init(Cipher.ENCRYPT_MODE, keyPublic);
        return cp.doFinal(data);
    }

    /**
     * 用公钥对字符串进行加密
     *
     * @param dataString 原文
     * @param publicKey 公钥
     * @return 密文
     */
    public static String encryptByPublicKey(String dataString, String publicKey) throws Exception{
        //64位解码加密后的字符串, 字符串转字节数组
        byte[] inputByte = Base64Utils.decodeToByte(dataString);
        //base64编码的公钥, 字符串转字节数组
        byte[] decoded = Base64Utils.decodeToByte(publicKey);
        return new String(encryptByPublicKey(inputByte, decoded));
    }


    /**
     * RSA公钥解密(先数据Base64解密，在RSA解密)
     *
     * @param data 待解密数据
     * @param publicKey 密钥
     * @return byte[] 解密后的明文数据
     */
    public static byte[] decryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {

        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(data);
        KeyFactory kf = KeyFactory.getInstance(RSA);
        PublicKey keyPublic = kf.generatePublic(keySpec);

        // RSA数据解密
        Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
        cipher.init(Cipher.DECRYPT_MODE, keyPublic);

        return cipher.doFinal(publicKey);
    }

    /**
     * RSA公钥解密(先数据Base64解密，在RSA解密)
     *
     * @param str 待解密数据
     * @param publicKey 密钥
     * @return byte[] 解密后的明文数据
     */
    public static String decryptByPublicKey(String str, String publicKey) throws Exception {

        //64位解码加密后的字符串
        byte[] inputByte = Base64Utils.decodeToByte(str);
        //base64编码的公钥
        byte[] decoded = Base64Utils.decodeToByte(publicKey);

        return new String(decryptByPublicKey(inputByte,decoded));
    }


    /**
     * 私钥加密
     *
     * @param data       待加密数据
     * @param privateKey 密钥
     * @return byte[] 加密数据
     */
    public static byte[] encryptByPrivateKey(byte[] data, byte[] privateKey) throws Exception {
        // 得到私钥
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
        KeyFactory kf = KeyFactory.getInstance(RSA);
        PrivateKey keyPrivate = kf.generatePrivate(keySpec);
        // 数据加密
        Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, keyPrivate);
        return cipher.doFinal(data);
    }

    /**
     * 使用私钥进行解密
     */
    public static byte[] decryptByPrivateKey(byte[] encrypted, byte[] privateKey) throws Exception {
        // 得到私钥
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
        KeyFactory kf = KeyFactory.getInstance(RSA);
        PrivateKey keyPrivate = kf.generatePrivate(keySpec);

        // 解密数据
        Cipher cp = Cipher.getInstance(ECB_PKCS1_PADDING);
        cp.init(Cipher.DECRYPT_MODE, keyPrivate);
        byte[] arr = cp.doFinal(encrypted);
        return arr;
    }
}
